<template>
	<div class="login">
		<div class="body">
			<div class="info">
				<p>欢迎登录</p>
				<p>XXXX管理系统</p>
			</div>
			<el-form
				:rules="rules"
				ref="ruleForm"
				:model="formInline"
				class="demo-form-inline"
			>
				<el-form-item label="" prop="userName">
					<el-input v-model="formInline.userName" placeholder="user name">
						<template #prefix>
							<el-icon><User /></el-icon>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="userPassword" label="">
					<el-input
						type="password"
						v-model="formInline.userPassword"
						placeholder="Password"
						showPassword
					>
						<template #prefix>
							<el-icon><Lock /></el-icon>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item class="button">
					<el-button type="primary" @click="onSubmit($event)">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";

import { login } from "@/api/manage.js";
import { toast } from "@/Utils/index.js";
import { setCookies } from "@/Utils/auth.js";

const router = useRouter();
const formInline = reactive({
	userName: "",
	userPassword: "",
});

const rules = reactive({
	userName: [
		{
			required: true,
			message: "请输入正确的用户名",
			trigger: "blur",
		},
	],
	userPassword: [
		{
			required: true,
			message: "密码填写错误",
			trigger: ["blur", "change"],
		},
	],
});

const ruleForm = ref(null);

// 登陆事件
function onSubmit(event) {
	event.preventDefault();
	ruleForm.value.validate((res) => {
		if (res) {
			login(formInline.userName, formInline.userPassword)
				.then((res) => {
					toast("登录成功");
					setCookies(res.token);

					router.push({
						path: "/",
					});
				})
				.catch((err) => {
					console.log(err);
				});
		} else {
			console.log(res);
		}
	});
}

// keyDwon事件

function keyDown(event) {
	if (event.keyCode === 13) {
		onSubmit(event);
	}
}

onMounted(() => {
	window.addEventListener("keydown", keyDown);
});
onUnmounted(() => {
	window.addEventListener("keydown", keyDown);
});
</script>

<style lang="less" scoped>
.login {
	height: 100%;
	background: url("@/assets/login1-bg.jpg") 0 0 / cover no-repeat;
	.body {
		width: 800px;
		height: 100%;
		margin: 0 auto;
		background-color: rgba(255, 255, 255, 0.5);
		position: relative;
		.info {
			width: 300px;
			height: 200px;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			font-size: 40px;
			font-weight: bold;
			position: absolute;
			top: 20%;
			left: 50%;
			margin-left: -150px;
			margin-top: -100px;
			color: #409acc;
		}
		.demo-form-inline {
			width: 400px;
			height: 200px;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-top: -100px;
			margin-left: -200px;
			.el-input {
				height: 60px;
				border-radius: 30px;
			}
			.el-button {
				width: 100%;
				height: 60px;
			}
		}
	}
}
</style>
